window.onload = function() {
  init();
};
var init = function() {
  initMagnifier();
};

var initMagnifier = (function() {
  var oImgWrap = document.getElementsByClassName('img-wrap')[0],
    oMapWrap = oImgWrap.getElementsByClassName('map-wrap')[0],
    oMapImg = oMapWrap.getElementsByClassName('map-img')[0],
    magWidth = getStyles(oMapWrap, 'width'),
    magHeight = getStyles(oMapWrap, 'height'),
    imgX = oImgWrap.offsetLeft,
    imgY = oImgWrap.offsetTop;
  addEvent(oImgWrap, 'mouseover', function(e) {
    // 划入后显示放大器
    oMapWrap.classList.add('show');
    // 一旦划入就定位位置，不影响《oImgWrap》内部的不断定位
    showMag(getXY(e).x, getXY(e).y);
    // 绑定滑动事件处理函数mouseMove
    addEvent(document, 'mousemove', mouseMove);
  });
  
  // 滑动事件
  function mouseMove(e) {
    showMag(
      getXY(e).x,
      getXY(e).y,
      getXY(e).mouseX,
      getXY(e).mouseY,
    );
  }
  
  function getXY(e) {
    return {
      // x、y代表当前鼠标相对于《oImgWrap》的位置
      x: pagePos(e).X - imgX - magWidth / 2,
      y: pagePos(e).Y - imgY - magHeight / 2,
      // 用于判断是否离开《oImgWrap》
      mouseX: pagePos(e).X - imgX,
      mouseY: pagePos(e).Y - imgY,
    };
  }
  
  //该函数用于给放大器和图片位置定位赋值，且通过mouseX, mouseY判断是否出《oImgWrap》
  function showMag(x, y, mouseX, mouseY) {
    oMapWrap.style.left = x + 'px';
    oMapWrap.style.top = y + 'px';
    oMapImg.style.left = -x + 'px';
    oMapImg.style.top = -y + 'px';
    if (mouseX && mouseY) {
      if (mouseX < 0 || mouseX > getStyles(oImgWrap, 'width') ||
        mouseY < 0 || mouseY > getStyles(oImgWrap, 'height')) {
        oMapWrap.classList.remove('show');
      }
    }
  }
  
  // 离开《oImgWrap》后的清除
  addEvent(oImgWrap, 'mouseout', function() {
    oMapWrap.className = 'map-wrap';
    removeEvent(document, 'mousemove', mouseMove);
  });
});
